package j.nawks.wx.api.utils;

import j.nawks.wx.api.message.support.WeixinConstant;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * 微信工具类,提供微信的基础API的相关方法
 * 
 * @author Nawks.J@Gmail.com
 * 
 */
public class WeixinUtils {

	/**
	 * 校验request包是否符合微信校验规则
	 * @see http://mp.weixin.qq.com/wiki/index.php?title=%E9%AA%8C%E8%AF%81%E6%B6%88%E6%81%AF%E7%9C%9F%E5%AE%9E%E6%80%A7
	 * @param request
	 * @param token
	 * @return
	 */
	public static boolean isReqLegel(HttpServletRequest request, String token) {
		return checkReqLegel(token,
				request.getParameter(WeixinConstant.PARAM_TIMESTAMP),
				request.getParameter(WeixinConstant.PARAM_NONCE),
				request.getParameter(WeixinConstant.PARAM_SIGNATURE));
	}

	/**
	 * <ul>
	 * <li>将token、timestamp、nonce三个参数进行字典序排序 ;</li>
	 * <li>将三个参数字符串拼接成一个字符串进行sha1加密 ;</li>
	 * <li>开发者获得加密后的字符串可与signature对比，标识该请求来源于微信;</li>
	 * </ul>
	 * 
	 * @param token
	 * @param timestamp
	 * @param nonce
	 * @param signature
	 * @return
	 */
	public static boolean checkReqLegel(String token, String timestamp,
			String nonce, String signature) {
		
		/**
		 * 若校验相关字符串中有空白字符串,则不通过校验
		 */
		if (StringUtils.isBlank(signature) || StringUtils.isBlank(timestamp)
				|| StringUtils.isBlank(nonce) || StringUtils.isBlank(token)) {
			return false;
		}

		String[] array = new String[] { token, timestamp, nonce };
		Arrays.sort(array);
		String code = StringUtils.join(array);
		String encode = null;
		try {
			byte[] digest = DigestUtils.getSha1Digest().digest(
					code.getBytes("UTF-8"));
			encode = Hex.encodeHexString(digest);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return encode != null && encode.equalsIgnoreCase(signature);
	}
}
